﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Newtonsoft.Json;
using modle;
using Windows.Devices.Geolocation;
using System.Threading.Tasks;
using System.Net.Http;
using System.Diagnostics;
using ModelClassLibrary;
using Windows.UI;
// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace SplitViewOptions
{
    public sealed partial class LocationUserControl : UserControl
    {
        public LocationUserControl()
        {
            this.InitializeComponent();
            setkeyword();
        }

        private async void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            setoriginsites();
            try
            {
                if (p!=null&&string.IsNullOrEmpty(p.Text))
                {
                    await Getlocation();
                }
            }
            catch(Exception ex)
            {

            }
           
        }
        public async Task<Geoposition> GetPosition()
        {
            //请求对位置的访问权
            var accessStatus = await Geolocator.RequestAccessAsync();
            //此时，窗口会弹出提示是否允许应用访问位置，如果用户不允许则抛出异常
            if (accessStatus != GeolocationAccessStatus.Allowed) throw new Exception();
            //实例化定位类，并设置经纬度精确度（单位：米），一般为零，为保护用户隐私，建议减少精确度
            var geolocator = new Geolocator { DesiredAccuracyInMeters = 0 };
            //异步获取设备位置，并将位置保存到变量中（Geoposition类型）
            var position = await geolocator.GetGeopositionAsync();
            //异步获取位置，保存到变量中


            //返回位置
            return position;
        }
        List<Info> sitelisst = new List<Info>();
        List<string> keywords = new List<string>();
        private void setkeyword()
        {
            keywords.Add("今天");
            keywords.Add("明天");
            keywords.Add("昨天");
            keywords.Add("最新");
            keywords.Add("未来");
            keywords.Add("现在");

            keywords.Add("物价");
            keywords.Add("房价");
            keywords.Add("大学");
            keywords.Add("日报");
            keywords.Add("晚报");
            keywords.Add("新闻网");
            keywords.Add("美女");
            keywords.Add("天气");
            keywords.Add("活动");
            keywords.Add("举行");
            keywords.Add("大事");
            keywords.Add("景点");
            keywords.Add("交通");
            keywords.Add("购物"); 
            keywords.Add("人社局");
            keywords.Add("论坛");
            keywords.Add("招聘");
            keywords.Add("出行");
            keywords.Add("电视台");
            keywords.Add("广播");
            keywords.Add("球队");
            keywords.Add("名人");
            keywords.Add("政府网");
            keywords.Add("科技");
            keywords.Add("人物");
            keywords.Add("音乐");
            keywords.Add("特产");
            keywords.Add("教育");
            keywords.Add("生意");
            keywords.Add("农村");
            keywords.Add("特色");
            keywords.Add("历史");
            keywords.Add("文化");
            keywordgridview.ItemsSource = keywords;
        }
        private void setoriginsites()
        {
            Info eight = new Info() { text = "百度网页", dataurl = "https://m.baidu.com/s?word=" };
            sitelisst.Add(eight);
            Info one = new Info() { text = "百度新闻", dataurl = "http://m.news.baidu.com/news?fr=mohome&ssid=a4e36769733738396d0f&from=&uid=&pu=sz%401320_2001%2Cta%40iphone_1_6.0_3_536&bd_page_type=1#search/" };
            sitelisst.Add(one);
            Info two = new Info() { text = "贴吧", dataurl = "http://tieba.baidu.com/f?kw=" };
            sitelisst.Add(two);
            Info three = new Info() { text = "图片", dataurl = "http://image.baidu.com/search/wisemidresult?tn=wisemidresult&ie=utf8&word=" };
            sitelisst.Add(three);
            Info f = new Info() { text = "微博用户", dataurl = "http://s.weibo.com/user/" };
            sitelisst.Add(f);
            Info five = new Info() { text = "微博内容", dataurl = "http://s.weibo.com/weibo/" };
            sitelisst.Add(five);
            //Info six = new Info() { text = "广播", dataurl = "http://www.qingting.fm/#/search/" };
            //sitelisst.Add(six);
            //Info today = new Info() { text = "今天", dataurl = "http://m.news.baidu.com/news?fr=mohome&ssid=0&from=&uid=&pu=sz%401320_2001%2Cta%40iphone_1_6.0_3_536&bd_page_type=1#search/" };
            //sitelisst.Add(today);            
            //Info tommorow = new Info() { text = "明天", dataurl = "http://m.news.baidu.com/news?fr=mohome&ssid=0&from=&uid=&pu=sz%401320_2001%2Cta%40iphone_1_6.0_3_536&bd_page_type=1#search/" };
            //sitelisst.Add(tommorow);
            //Info yesterday = new Info() { text = "昨天", dataurl = "http://m.news.baidu.com/news?fr=mohome&ssid=0&from=&uid=&pu=sz%401320_2001%2Cta%40iphone_1_6.0_3_536&bd_page_type=1#search/" };
            //sitelisst.Add(yesterday);
            //Info zuixin = new Info() { text = "最新", dataurl = "http://m.news.baidu.com/news?fr=mohome&ssid=0&from=&uid=&pu=sz%401320_2001%2Cta%40iphone_1_6.0_3_536&bd_page_type=1#search/" };
            //sitelisst.Add(zuixin);
            //Info now = new Info() { text = "现在", dataurl = "http://m.news.baidu.com/news?fr=mohome&ssid=0&from=&uid=&pu=sz%401320_2001%2Cta%40iphone_1_6.0_3_536&bd_page_type=1#search/" };
            //sitelisst.Add(now);
            //Info futture = new Info() { text = "未来", dataurl = "http://m.news.baidu.com/news?fr=mohome&ssid=0&from=&uid=&pu=sz%401320_2001%2Cta%40iphone_1_6.0_3_536&bd_page_type=1#search/" };
            //sitelisst.Add(futture);
            //Info xiangcun = new Info() { text = "农村", dataurl = "http://m.news.baidu.com/news?fr=mohome&ssid=0&from=&uid=&pu=sz%401320_2001%2Cta%40iphone_1_6.0_3_536&bd_page_type=1#search/" };
            //sitelisst.Add(xiangcun);
            gridview.ItemsSource = sitelisst;
        }
         private async Task Getlocation()
        {
            try
            {

                //await App.showmessage("定位中");
                messagetb.Text = "开始定位";
                var position = await GetPosition();
                //维度
                double lat = position.Coordinate.Point.Position.Latitude;
                //经度
                double lon = position.Coordinate.Point.Position.Longitude;
                messagetb.Text = "经纬度：" + lat.ToString() + "," + lon.ToString();
                //await App.showmessage("经纬度：" + lat.ToString() + "," + lon.ToString());
                string geocodeurl = "http://api.map.baidu.com/geocoder/v2/?ak=6kvn8vZN6KFaxcMErHGLb7H5&location=" + lat.ToString() + "," + lon.ToString() + "&output=json&pois=0";
                HttpClient adressclient = new HttpClient();

                var myRequest = new HttpRequestMessage(HttpMethod.Get, geocodeurl);
                myRequest.Version = Version.Parse("1.1");
                Debug.WriteLine(myRequest.Version.ToString());
                // await App.showmessage("获取地址中");
                messagetb.Text = "获取地址中";
                var response = await adressclient.SendAsync(myRequest);
                string streamcontent = await response.Content.ReadAsStringAsync();
                BaiduAdresslocatejson deserializedProduct = (BaiduAdresslocatejson)JsonConvert.DeserializeObject(streamcontent, typeof(BaiduAdresslocatejson));
                string distrtict = deserializedProduct.result.addressComponent.district;
                string cityname = deserializedProduct.result.addressComponent.city;
                // L.Text = deserializedProduct.result.formatted_address;
                p.Text = deserializedProduct.result.addressComponent.province;
                c.Text = deserializedProduct.result.addressComponent.city;
                x.Text = deserializedProduct.result.addressComponent.district;
                l.Text = deserializedProduct.result.addressComponent.street;
                locatestr = deserializedProduct.result.formatted_address;
                messagetb.Visibility = Visibility.Collapsed;
            }
            catch(Exception ex) {  }
            }
        string selectedtxt = "";
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            string str = btn.Content.ToString();
            Info btninfo = btn.DataContext as Info;
            string url = btninfo.dataurl + btn.Content.ToString();
            App.Currenturl = new Uri(url, UriKind.RelativeOrAbsolute);
            App.Mainframe.Navigate(typeof(HomePage));
        //    if (str== "百度新闻")
        //    {
        //        string url = "http://news.baidu.com/ns?word="+ selectedtxt;
        //        App.currenturl = new Uri(url, UriKind.RelativeOrAbsolute);
        //        App.mainframe.Navigate(typeof(HomePage));
        //    }
        //else    if (str == "百度贴吧")
        //    {
        //        string url = "http://tieba.baidu.com/f?kw=" + selectedtxt;
        //        App.currenturl = new Uri(url, UriKind.RelativeOrAbsolute);
        //        App.mainframe.Navigate(typeof(HomePage));
        //    }
        //    else if (str == "百度图片")
        //    {
        //        string url = "http://image.baidu.com/search/index?tn=baiduimage&ct=201326592&lm=-1&cl=2&word=" + selectedtxt;
        //        App.currenturl = new Uri(url, UriKind.RelativeOrAbsolute);
        //        App.mainframe.Navigate(typeof(HomePage));
        //    }
        //    else if (str == "微博用户")
        //    {
        //        string url = "http://s.weibo.com/user/" + selectedtxt;
        //        App.currenturl = new Uri(url, UriKind.RelativeOrAbsolute);
        //        App.mainframe.Navigate(typeof(HomePage));
        //    }
        //    else if (str == "微博内容")
        //    {
        //        string url = "http://s.weibo.com/weibo/" + selectedtxt;
        //        App.currenturl = new Uri(url, UriKind.RelativeOrAbsolute);
        //        App.mainframe.Navigate(typeof(HomePage));
        //    }
        //    else if (str == "广播")
        //    {
        //        string url = "http://www.qingting.fm/#/search/" + selectedtxt;
        //        App.currenturl = new Uri(url, UriKind.RelativeOrAbsolute);
        //        App.mainframe.Navigate(typeof(HomePage));
        //    }
        //    else
        //    {
        //        Info btninfo= btn.DataContext as Info;
        //        string url = btninfo.dataurl+btn.Content.ToString();
        //        App.currenturl = new Uri(url, UriKind.RelativeOrAbsolute);
        //        App.mainframe.Navigate(typeof(HomePage));
        //    }


        }

        private void Border_Tapped(object sender, TappedRoutedEventArgs e)
        {
            Border obj = sender as Border;
            Info oneinfo = obj.DataContext as Info;
            string str = oneinfo.text.ToString();
            if(string.IsNullOrEmpty(addresstr))
            {
                addresstr = c.Text;
            }
            selectedtxt = addresstr + keyword;
            if (str == "百度新闻")
            {
                string url = "http://m.news.baidu.com/news?fr=mohome&ssid=a4e36769733738396d0f&from=&uid=&pu=sz%401320_2001%2Cta%40iphone_1_6.0_3_536&bd_page_type=1#search/" + selectedtxt;
                App.Currenturl = new Uri(url, UriKind.RelativeOrAbsolute);
                App.Mainframe.Navigate(typeof(HomePage));
            }
           else if (str == "百度网页")
            {
                string url = "https://m.baidu.com/s?word=" + selectedtxt;
                App.Currenturl = new Uri(url, UriKind.RelativeOrAbsolute);
                App.Mainframe.Navigate(typeof(HomePage));
            }
         
            else if (str == "贴吧")
            {
                string url = "http://tieba.baidu.com/f?kw=" + selectedtxt;
                App.Currenturl = new Uri(url, UriKind.RelativeOrAbsolute);
                App.Mainframe.Navigate(typeof(HomePage));
            }
            else if (str == "图片")
            {
                string url = "http://image.baidu.com/search/wisemidresult?tn=wisemidresult&ie=utf8&word=" + selectedtxt;
                App.Currenturl = new Uri(url, UriKind.RelativeOrAbsolute);
                App.Mainframe.Navigate(typeof(HomePage));
            }
            else if (str == "微博用户")
            {
                string url = "http://s.weibo.com/user/" + selectedtxt;
                App.Currenturl = new Uri(url, UriKind.RelativeOrAbsolute);
                App.Mainframe.Navigate(typeof(HomePage));
            }
            else if (str == "微博内容")
            {
                string url = "http://s.weibo.com/weibo/" + selectedtxt;
                App.Currenturl = new Uri(url, UriKind.RelativeOrAbsolute);
                App.Mainframe.Navigate(typeof(HomePage));
            }
            else if (str == "广播")
            {
                string url = "http://www.qingting.fm/#/search/" + selectedtxt;
                App.Currenturl = new Uri(url, UriKind.RelativeOrAbsolute);
                App.Mainframe.Navigate(typeof(HomePage));
            }
            else
            {
               
                string url = oneinfo.dataurl + oneinfo.text;
                App.Currenturl = new Uri(url, UriKind.RelativeOrAbsolute);
                App.Mainframe.Navigate(typeof(HomePage));
            }
            
        }
        string locatestr = string.Empty;
        string addresstr = string.Empty;
        private void p_Tapped(object sender, TappedRoutedEventArgs e)
        {
            TextBlock tb = sender as TextBlock;
            tb.Foreground = new SolidColorBrush(Colors.Red);
            string str = tb.Text;
            addresstr = str;
            locatestr = tb.Text;
            //selectedtxt = str+ keyword;
        }
        string keyword = string.Empty;
        private void keywordBorder_Tapped(object sender, TappedRoutedEventArgs e)
        {
            TextBlock tbf = sender as TextBlock;
            tbf.Foreground = new SolidColorBrush(Colors.Red);
            string str = tbf.Text;
            keyword = str;
            //if (string.IsNullOrEmpty(selectedtxt))
            //{
            //    selectedtxt = c.Text;
            //}
            //selectedtxt = selectedtxt + keyword;
        }
    }
}
